package fina2.dcs.menu;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import fina2.dcs.context.ContextHelper;
import fina2.dcs.security.RoleLocal;
import fina2.dcs.security.UserLocal;

@Name("menuManager")
@Scope(ScopeType.SESSION)
public class MenuManager implements Serializable{
	private String pageUrl = "../security/data.seam";
	private String label = "Data";

	private Log log = Logging.getLog(getClass());

	private List<MenuManager> menuItems = new ArrayList<MenuManager>();

	private InitialContext ic = null;

	private UserLocal ul;
	private RoleLocal rl;

	public MenuManager() {
		try {
			ic = ContextHelper.getInitialContext();
			ul = ContextHelper.injectUserLocal(ic);
			rl = ContextHelper.injectRoleLocal(ic);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public MenuManager(String label, String pageUrl) {
		this.label = label;
		this.pageUrl = pageUrl;
	}

	public String getPageUrl() {
		return pageUrl;
	}

	public void setPageUrl(String pageUrl) {
		log.info("#############################"+pageUrl);
		this.pageUrl = "../security/" + pageUrl;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public List<MenuManager> loadMenuItems(Object prefix) {
		menuItems.add(new MenuManager("Data", "../security/data.seam"));
		if (ul.hasPermission("fina2.bank.review")) {
			menuItems.add(new MenuManager("Fi Types", "../security/bankTypes.seam"));
			menuItems.add(new MenuManager("Fi List", "../security/fiList.seam"));
			menuItems.add(new MenuManager("Fi Groups", "../security/fiGroups.seam"));
			menuItems.add(new MenuManager("License Types", "../security/licenceTypes.seam"));
		}
		if (ul.hasPermission("fina2.periods.review"))
			menuItems.add(new MenuManager("Period Types", "../security/periodTypes.seam"));
		if (ul.hasPermission("fina2.returns.review"))
			menuItems.add(new MenuManager("Return Manager", "../security/returnManager.seam"));
		if (ul.hasPermission("fina2.returns.version.review"))
			menuItems.add(new MenuManager("Return Versions", "../security/returnVersions.seam"));
		for (int i = 0; i < menuItems.size(); i++) {
			if (!menuItems.get(i).getLabel().trim().toLowerCase().contains(prefix.toString().trim().toLowerCase())) {
				menuItems.remove(i);
				i--;
			}
		}
		return menuItems;
	}
}
